import { GenerateOption } from "../generateOption";


/**
 * 扩展对window, dialog, panel, Layout, tabs, accordion控件内容可绑定ko组件的能力
 */
export class ExtendBind{
    private option;
    private jquery;
    private ko; 
    constructor(option:GenerateOption){
        this.option = option;
        this.jquery = option.jquery;
        this.ko = option.ko; 
    }
    extend(name, opts,bindContext){
        let eName = this._getEventName(name);
        if(eName){
            this._extendOption(eName, opts, bindContext);
        }
    }
    /**
     * 获取可扩展的事件名称
     */
    _getEventName = function(name){
        let eventName = null;
        switch(name){
            case "window":
            case "dialog":
            case "layout":
            case "panel":
                eventName = "onBeforeOpen";
                break;
            case "tabs":
            case "accordion":
                eventName = "onAdd";
                break;
        }
        return eventName;
    }
    /**
     * 将指定的事件扩展为支持ko组件自动绑定的能力
     * @param eName 事件名称
     * @param opts 配置参数
     * @param bindContext ko组件上下文
     */
    _extendOption(eName, opts,bindContext){ 
        let that = this;
        if(opts.viewModel){ 
            //说明有ko组件需要绑定
            let _orgEvent = opts[eName];
            opts[eName] = function(){
                
                //viewModel必须是对象
                let childBindContext = bindContext.createChildContext(opts.viewModel,undefined,function(ctx){
                });
                //@ts-ignore
                that.ko.applyBindingsToDescendants(childBindContext,this);//调用者，肯定是组件
                _orgEvent && _orgEvent.apply(childBindContext.$data, arguments); //执行开发者配置的事件
            };
        }
    }
}